package com.chenshang.service.base;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chenshang.service.inter.IHttpService;

public class HttpService implements IHttpService {
	private static Logger LOGGER = LoggerFactory.getLogger(HttpService.class);

	@Override
	public String sendPostHttpRequest(String url, String requestParams) {
		@SuppressWarnings("resource")
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		StringEntity entity = new StringEntity(requestParams, "utf-8");
		entity.setContentEncoding("UTF-8");
		httpPost.setEntity(entity);
		try {
			HttpResponse httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getEntity() != null)
				return EntityUtils.toString(httpResponse.getEntity());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.info("Http请求失败");
		}
		return null;
	}

	@Override
	public String sendGetHttpRequest(String url, String requestParams) {
		try {
			@SuppressWarnings({ "resource" })
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getEntity() != null)
				return EntityUtils.toString(httpResponse.getEntity());
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.info("Http请求失败");
		}
		return null;
	}
}
